#include <iostream>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <cstring>

void childwrite(int wfd)
{
    char buffer[1024];
    int cnt = 0;
    while(1)
    {
        snprintf(buffer, sizeof(buffer), 
        "I am the child, my pid_t is %d, my counter is %d", 
        getpid(), cnt++);

        write(wfd, buffer, strlen(buffer));
        sleep(1);
    }
}

void fatherread(int rfd)
{
    char buffer[1024];
    while(1)
    {
        int n = read(rfd, buffer, sizeof(buffer) - 1);
        if(n > 0)
        {
            buffer[n] = 0;
        }
        std::cout << "child says:" << buffer << std::endl;
    }
}

int main()
{
    int fds[2] = {0};

    int n = pipe(fds);
    std::cout << "fds[0]" << fds[0] 
    << "fds[1]"<< fds[1] << std::endl;
    if(n < 0)
    {
        std::cerr << "pipe fail";
        return 1;
    }

    pid_t id = fork();
    if(id == 0)
    {
        close(fds[0]);
        childwrite(fds[1]);
        close(fds[1]);
        exit(0);
    }
    close(fds[1]);
    fatherread(fds[0]);
    waitpid(id, nullptr, 0);
    close(fds[0]);
    
    return 0;
}